/**
 * Pinia 是一个用于 Vue 的状态管理库
 * 参考链接：https://segmentfault.com/a/1190000040373313?utm_source=sf-similar-article
 */

import { defineStore } from 'pinia';

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const useSourceStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'source-store',
  // state: 返回对象的函数
  state: () => ({
    recoverSourceData: {}, //复原数据源
    sourceData: {}, //数据源
    sourceCode: '', //数据源编码
  }),
  getters: {
    source(state) {
      return {
        sourceData: state.sourceData,
        sourceCode: state.sourceCode,
        recoverSourceData: state.recoverSourceData,
      };
    },
  },
  actions: {
    //根据数据源code缓存配置
    setSourceDataByCode(sourceCode, sourceItemData) {
      this.sourceData[sourceCode] = { ...sourceItemData };
    },
    //根据数据源code获取对应数据
    getSourceDataByCode(sourceCode) {
      return this.sourceData[sourceCode];
    },
    //设置当前资源表code
    setSourceCode(sourceCode) {
      this.sourceCode = sourceCode;
    },
    //获取当前数据源的code
    getSourceCode() {
      return this.sourceCode;
    },
    //清空当前数据源(当切换产的时，需要清空之前产品下的数据源)
    initSourceData() {
      this.sourceData = {};
      this.recoverSourceData = {};
    },
    //删除当前store中对应的数据源数据
    removeDataByCode(sourceCode) {
      delete this.sourceData[sourceCode];
      delete this.recoverSourceData[sourceCode];
    },
    //根据数据源code缓存复原配置
    setRecoverSourceDataByCode(sourceCode, sourceItemData) {
      this.recoverSourceData[sourceCode] = { ...sourceItemData };
    },
    //根据数据源code获取对应复原数据
    getRecoverSourceDataByCode(sourceCode) {
      return this.recoverSourceData[sourceCode];
    },
  },
});
